package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.libalipay.PayManager;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.User;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Charge;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.squareup.okhttp.Request;

import de.greenrobot.event.EventBus;


public class MainProfileBalanceChargeLayout extends LinearLayout {

    private final CheckBox ckCharge10, ckCharge20, ckCharge50, ckCharge100, ckCharge200, ckCharge500;
    private final TextView txBalance, txTip;
    private Float amount;
    private float result;

    private float mSelectedValue = -1;

    public MainProfileBalanceChargeLayout(Context context) {
        this(context, null);
    }

    public MainProfileBalanceChargeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
            }
        });
        LayoutInflater.from(context).inflate(R.layout.layout_main_profile_balance_charge, this);
//        ((ViewGroup) getChildAt(0)).getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        findViewById(R.id.btn_submit).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedValue > 0) {
                    requestOrderCharge();
                } else {
                    BaseUtil.showToast(R.string.balance_charge_tip_default);
                }
            }
        });


        ckCharge10 = (CheckBox) findViewById(R.id.ck_charge_10);
        ckCharge20 = (CheckBox) findViewById(R.id.ck_charge_20);
        ckCharge50 = (CheckBox) findViewById(R.id.ck_charge_50);
        ckCharge100 = (CheckBox) findViewById(R.id.ck_charge_100);
        ckCharge200 = (CheckBox) findViewById(R.id.ck_charge_200);
        ckCharge500 = (CheckBox) findViewById(R.id.ck_charge_500);

        View.OnClickListener l = new OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()) {
                    case R.id.ck_charge_10:
                        mSelectedValue = 10;
                        ckCharge10.setChecked(true);
                        ckCharge10.setTextColor(0xFFFFFFFF);
                        ckCharge20.setTextColor(0xFF05131A);
                        ckCharge20.setChecked(false);
                        ckCharge50.setTextColor(0xFF05131A);
                        ckCharge50.setChecked(false);
                        ckCharge100.setTextColor(0xFF05131A);
                        ckCharge100.setChecked(false);
                        ckCharge200.setTextColor(0xFF05131A);
                        ckCharge200.setChecked(false);
                        ckCharge500.setTextColor(0xFF05131A);
                        ckCharge500.setChecked(false);
                        break;
                    case R.id.ck_charge_20:
                        mSelectedValue = 20;
                        ckCharge20.setChecked(true);
                        ckCharge20.setTextColor(0xFFFFFFFF);
                        ckCharge10.setTextColor(0xFF05131A);
                        ckCharge10.setChecked(false);
                        ckCharge50.setTextColor(0xFF05131A);
                        ckCharge50.setChecked(false);
                        ckCharge100.setTextColor(0xFF05131A);
                        ckCharge100.setChecked(false);
                        ckCharge200.setTextColor(0xFF05131A);
                        ckCharge200.setChecked(false);
                        ckCharge500.setTextColor(0xFF05131A);
                        ckCharge500.setChecked(false);
                        break;
                    case R.id.ck_charge_50:
                        mSelectedValue = 50;
                        ckCharge50.setChecked(true);
                        ckCharge50.setTextColor(0xFFFFFFFF);
                        ckCharge10.setTextColor(0xFF05131A);
                        ckCharge10.setChecked(false);
                        ckCharge20.setTextColor(0xFF05131A);
                        ckCharge20.setChecked(false);
                        ckCharge100.setTextColor(0xFF05131A);
                        ckCharge100.setChecked(false);
                        ckCharge200.setTextColor(0xFF05131A);
                        ckCharge200.setChecked(false);
                        ckCharge500.setTextColor(0xFF05131A);
                        ckCharge500.setChecked(false);
                        break;
                    case R.id.ck_charge_100:
                        mSelectedValue = 100;
                        ckCharge100.setChecked(true);
                        ckCharge100.setTextColor(0xFFFFFFFF);
                        ckCharge10.setTextColor(0xFF05131A);
                        ckCharge10.setChecked(false);
                        ckCharge20.setTextColor(0xFF05131A);
                        ckCharge20.setChecked(false);
                        ckCharge50.setTextColor(0xFF05131A);
                        ckCharge50.setChecked(false);
                        ckCharge200.setTextColor(0xFF05131A);
                        ckCharge200.setChecked(false);
                        ckCharge500.setTextColor(0xFF05131A);
                        ckCharge500.setChecked(false);
                        break;
                    case R.id.ck_charge_200:
                        mSelectedValue = 200;
                        ckCharge200.setChecked(true);
                        ckCharge200.setTextColor(0xFFFFFFFF);
                        ckCharge10.setTextColor(0xFF05131A);
                        ckCharge10.setChecked(false);
                        ckCharge20.setTextColor(0xFF05131A);
                        ckCharge20.setChecked(false);
                        ckCharge50.setTextColor(0xFF05131A);
                        ckCharge50.setChecked(false);
                        ckCharge100.setTextColor(0xFF05131A);
                        ckCharge100.setChecked(false);
                        ckCharge500.setTextColor(0xFF05131A);
                        ckCharge500.setChecked(false);
                        break;
                    case R.id.ck_charge_500:
                        mSelectedValue = 500;
                        ckCharge500.setChecked(true);
                        ckCharge500.setTextColor(0xFFFFFFFF);
                        ckCharge10.setTextColor(0xFF05131A);
                        ckCharge10.setChecked(false);
                        ckCharge20.setTextColor(0xFF05131A);
                        ckCharge20.setChecked(false);
                        ckCharge50.setTextColor(0xFF05131A);
                        ckCharge50.setChecked(false);
                        ckCharge100.setTextColor(0xFF05131A);
                        ckCharge100.setChecked(false);
                        ckCharge200.setTextColor(0xFF05131A);
                        ckCharge200.setChecked(false);
                        break;
                }

                txTip.setText(getContext().getString(R.string.balance_charge_tip, (int) mSelectedValue));
            }
        };

        ckCharge10.setOnClickListener(l);
        ckCharge20.setOnClickListener(l);
        ckCharge50.setOnClickListener(l);
        ckCharge100.setOnClickListener(l);
        ckCharge200.setOnClickListener(l);
        ckCharge500.setOnClickListener(l);


        txBalance = (TextView) findViewById(R.id.tx_balance);
        txTip = (TextView) findViewById(R.id.tx_tip);
        initWallet();
    }

    private void initWallet() {
        com.paishen.peiniwan.database.User user = App.i().getUser();
        amount = user.getAmount();

        result = amount != null ? amount.floatValue() : 0;

        txBalance.setText(getContext().getString(R.string.date_pay_value_2, String.valueOf((int) result)));
    }

    private void requestOrderCharge() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).create();
        dlgLoading.show();
        PnwHttpManager.Order.recharge(((BaseActivity) getContext()).TAG, (int) mSelectedValue, new PnwOkCallbackAdapter<HttpRespData<Charge>>() {
            @Override
            public void onResponse(HttpRespData<Charge> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    requestAliPay(response.data.out_trade_no);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void requestAliPay(String tradeNo) {
        float price = mSelectedValue;

        if (App.DEBUG_MODE) price = 0.01f; // test

        final float mValue = price;
        String body = String.valueOf(App.i().getUser().getId()) + ",recharge";
        String serverUrl = PnwHttpManager.URL_SERVICE_PAY_NOTIFY;
        LogUtil.t("requestAliPay(price:" + price + " #serverUrl:" + serverUrl + ")");

        PayManager.pay(((BaseActivity) getContext()), tradeNo, mValue, App.i().getString(R.string.charge_name), body, serverUrl
                , new PayManager.PayResultListener() {
            @Override
            public void onSuccess() {
                User login = App.i().getUser();
                int result = login.getAmount() != null ? (int) login.getAmount().floatValue() : 0;
                login.setAmount(result + mValue);

                initWallet();

                EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, login));
                EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_BALANCE_BY_CHARGE));

                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ((BaseActivity) getContext()).onBackPressed();
                    }
                },400);
            }

            @Override
            public void onDealing() {
            }

            @Override
            public void onFail() {
            }
        });
    }

}
